package cn.tedu.tmall.admin.mall.controller;

import cn.tedu.tmall.admin.mall.pojo.param.CategoryAddNewParam;
import cn.tedu.tmall.admin.mall.pojo.vo.CategoryListItemVO;
import cn.tedu.tmall.admin.mall.pojo.vo.CategoryStandardVO;
import cn.tedu.tmall.admin.mall.service.ICategoryService;
import cn.tedu.tmall.common.pojo.vo.PageData;
import cn.tedu.tmall.common.web.JsonResult;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Api(tags = "1. 类别管理")
@Validated
@RestController
@RequestMapping("/categories")
public class CategoryController {

    @Autowired
    private ICategoryService categoryService;

    @ApiOperation("新增类别")
    @ApiOperationSupport(order = 100)
    @PostMapping("/add-new")
    public JsonResult addNew(@Valid CategoryAddNewParam categoryAddNewParam) {
        categoryService.addNew(categoryAddNewParam);
        return JsonResult.ok();
    }

    @ApiOperation("根据ID查询类别详情")
    @ApiOperationSupport(order = 410)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "类别ID", required = true, dataType = "long")
    })
    @GetMapping("/{id:[0-9]+}")
    @PreAuthorize("hasAuthority('/mall/category/simple')")
    public JsonResult getStandardById(@Range(min = 1, message = "查询类别详情失败，请提交有效的类别ID值！")
                                      @PathVariable Long id) {
        CategoryStandardVO queryResult = categoryService.getStandardById(id);
        return JsonResult.ok(queryResult);
    }

    @ApiOperation("根据父级查询子级类别列表")
    @ApiOperationSupport(order = 420)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "parentId", value = "父级类别ID", required = true, dataType = "long"),
            @ApiImplicitParam(name = "page", value = "页码", dataType = "int")
    })
    @GetMapping("/list-by-parent")
    public JsonResult listByParent(@RequestParam @Range(message = "根据父级查询子级类别列表失败，请提交有效的父级类别ID值！") Long parentId, Integer page) {
        Integer pageNum = page;
        if (page == null || page < 1) {
            pageNum = 1;
        }
        PageData<CategoryListItemVO> list = categoryService.listByParent(parentId, pageNum);
        return JsonResult.ok(list);
    }

}